import { useEffect, useState } from "react"
import {
  Button,
  Form,
  Divider,
  Select,
  Row,
  Col,
  Input,
  message,
  DatePicker,
  Alert,
  notification
} from "antd"
import Marquee from "react-fast-marquee"
import { SmileOutlined } from "@ant-design/icons"
// import Application from "../conferenceList/index"
// import { getDeparment, postAddbook } from "@/api/index"
import dayjs from "dayjs"
import { useNavigate } from "react-router-dom"
import customParseFormat from "dayjs/plugin/customParseFormat"
import Tablemodel from "../conferenceList/tableClo/index"
import {
  postAddbook, //会议添加接口
  getDeparment, //部门数据
  usetype, //申请类型
  TypeClass //会议教室
} from "@/api/modules/conference/index.jsx"
import Times from "./Times" //时间函数
const Index = () => {
  const [Timemintus, setTimehours] = useState([]) //分钟禁用
  // 教室选择
  const [Classroom, setClassroom] = useState("")
  const Changeroom = async (val) => {
    console.log(val, "教师")
    setClassroom(val)
  }
  // 表单添加
  const onFinish = async (values) => {
    // 登录用户
    let apply_name = JSON.parse(localStorage.getItem("user")).username
    // console.log(apply_name, "登陆数据")
    // console.log("Success:", values)
    const addBook = values
    let starTime = values.apply_time[0].$d
    let endTime = values.apply_time[1].$d
    let startTime = Times(starTime)
    let endTime1 = Times(endTime)
    addBook.use_start_time = startTime
    addBook.use_end_time = endTime1
    addBook.apply_name = apply_name
    delete addBook.apply_time
    console.log(addBook, "addBook")
    // 会议添加,bookCreate
    let addbooks = await postAddbook(addBook) //
    console.log(addbooks, "48")
    if (addbooks.code == 200) {
      addSuccess("success", "预约成功")
    } else {
      addSuccess("error", "预约失败")
    }
    // await postAddbook(addBook)
  }
  const onFinishFailed = (errorInfo) => {
    // console.log("Failed:", errorInfo)
  }
  // 弹框
  const [messageApi, contextHolder] = message.useMessage()
  const addSuccess = (success, ok) => {
    messageApi.open({
      type: success,
      content: ok,
      duration: 10
    })
  }
  const navigate = useNavigate()
  // 时间组件
  dayjs.extend(customParseFormat)
  const { RangePicker } = DatePicker
  const range = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }

  // eslint-disable-next-line arrow-body-style
  // 禁用号
  const disabledDate = (current) => {
    // console.log("点击了吗？几号：", current, "type")

    // Can not select days before today and seven days after today
    const today = dayjs().startOf("day")
    const maxDate = today.add(6, "day")
    return current && (current.isBefore(today, "day") || current.isAfter(maxDate, "day"))
  }

  // 选择禁用时间
  const disabledRangeTime = (val, type) => {
    // console.log("点击了吗？日期", "type", type, Timemintus)
    if (type === "start") {
      return {
        // disabledHours: () => range(0, 60).splice(4, 20),
        disabledMinutes: () => [...Timemintus],
        disabledSeconds: () => range(1, 60)
      }
    }
    return {
      // disabledHours: () => range(0, 60).splice(20, 4),
      disabledMinutes: () => [...Timemintus],
      disabledSeconds: () => range(1, 60)
    }
  }

  // 部门数据，使用类型数据，会议教室数据 typeList
  const [deptsd, setdeptsd] = useState([]) //部门
  const [typeList, settypeList] = useState([]) //使用类型
  const [TypeClassd, setTypeClassd] = useState([]) //会议教室数据
  const detons = async () => {
    const typeList = await usetype() //使用类型数据
    const depts = await getDeparment() //部门
    const TypeClassroom = await TypeClass()
    console.log(TypeClass, "53", depts)
    setTypeClassd(TypeClassroom.data)
    settypeList(typeList.data)
    setdeptsd(depts.data)
  }

  // 时间限制
  const [TimeLimit, setTimeLimit] = useState(JSON.parse(localStorage.getItem("bookDay")) || [])
  // ok事件 TimeLimit  Times(date[1].$d)
  const handleHourClick = (date) => {
    if (TimeLimit) {
      console.log(date[0].$D, "OK选择的日期:", date[0].$H)
      var timeSerch = TimeLimit.find((item, index) => Number(item.days) == date[0].$D) //号期
      console.log(TimeLimit, "时间搜索a", timeSerch)
      if (date[0].$H) {
        console.log("时间搜索", timeSerch)
        console.log(timeSerch, date[0].$H)
        var Hourslimt = timeSerch.hours.find((items, index) => Number(items.hours) == date[0].$H)
        const limtday = Hourslimt.minutes.map((str) => Number(str))
        console.log(Hourslimt, "分钟限制", limtday)
        setTimehours(limtday)
        // 分钟校验
        var Minuteslimt = Hourslimt.minutes.find((items, index) => Number(items) == date[0].$m)
        if (Minuteslimt) {
          console.log(Minuteslimt, "分钟村子啊")
          openNotification("您预约的时间已经预约请重新预约！")
          setTimehours(limtday)
        } else {
          // setTimehours([])
          openNotification("您预约选择的时间可以预约，确认进入下一步")
        }
      }
    } else {
      setTimehours([])
    }

    // 在这里执行点击日期单元格时获取日期数据的逻辑
  }
  // 预约时间警告
  const [api, contextHolders] = notification.useNotification()
  const openNotification = (val) => {
    api.open({
      message: "",
      description: val,
      icon: (
        <SmileOutlined
          style={{
            color: "#e9c910"
          }}
        />
      )
    })
  }
  useEffect(() => {
    detons() //部门数据函数
  }, [])
  return (
    <div>
      <div style={{ textAlign: "left" }}>
        <div>
          <h2>会议申请</h2>
        </div>
      </div>
      <div style={{ marginTop: "40px" }}>
        {/* from表单 */}
        <Form
          name="basic"
          labelCol={{
            span: 4
          }}
          wrapperCol={{
            span: 800
          }}
          style={{
            maxWidth: 1200
          }}
          initialValues={{
            remember: true
          }}
          onFinish={onFinish}
          onFinishFailed={onFinishFailed}
          autoComplete="off"
        >
          <Form.Item>
            <Row>
              <Col xs={24} sm={12} md={8} lg={7}>
                <Form.Item
                  label="会议室名称"
                  name="conference_theme"
                  rules={[
                    {
                      required: true,
                      message: "您申请的会议名称未填!"
                    }
                  ]}
                >
                  {/* 会议名称 */}
                  <Select
                    fieldNames={{
                      label: "type_Class",
                      value: "type_Class"
                    }}
                    defaultValue="千人报告厅"
                    style={{ width: 120 }}
                    onChange={Changeroom}
                    options={TypeClassd}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
          <Divider orientation="left">
            <h4>已申请列表</h4>
          </Divider>
          {/* 申请列表 */}
          <Tablemodel classrooms={Classroom} />
          {/* 使用类型   会议主题 */}
          <Form.Item>
            <Row>
              <Col xs={24} sm={12} md={8} lg={7}>
                {/* 使用类型 */}
                <Form.Item
                  label="使用类型"
                  name="use_type"
                  rules={[
                    {
                      required: true,
                      message: "使用类型未填！"
                    }
                  ]}
                >
                  <Select
                    fieldNames={{
                      label: "type_name",
                      value: "_id"
                    }}
                    options={typeList}
                    defaultValue="655e333bc44fbd3bafb19b8a"
                    style={{ width: 120 }}
                  />
                </Form.Item>
              </Col>
              {/* 会议主题 */}
              <Col>
                <Form.Item
                  label="会议主题"
                  name="conference_name"
                  rules={[
                    {
                      required: true,
                      message: "会议主题未填！"
                    }
                  ]}
                >
                  <Input />
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
          {/* 使用时间   申请部门 */}
          <Form.Item>
            <Row>
              <Col xs={24} sm={12} md={8} lg={8}>
                <Form.Item
                  label="申请时间"
                  name="apply_time"
                  rules={[
                    {
                      required: true,
                      message: "请设置使用时间！"
                    }
                  ]}
                >
                  {/* 时间组件 */}
                  <RangePicker
                    disabledDate={disabledDate}
                    disabledTime={disabledRangeTime}
                    showTime={{
                      hideDisabledOptions: true,
                      format: "HH:mm"
                    }}
                    allowClear={true} // 禁用清除按钮，使用户必须选择日期才能触发
                    // renderExtraFooter={null}
                    onOk={handleHourClick}
                    // 其他属性
                    renderExtraFooter={() => (
                      <Alert
                        banner
                        message={
                          <Marquee pauseOnHover gradient={false}>
                            如果没有您想预约的时间，那是时间被预约了！
                          </Marquee>
                        }
                      />
                    )}
                  />
                </Form.Item>
              </Col>
              <Col>
                <Form.Item
                  label="部门申请"
                  name="apply_department"
                  rules={[
                    {
                      required: true,
                      message: "申请部门未填！"
                    }
                  ]}
                >
                  {/* 申请部门 */}
                  <Select
                    fieldNames={{
                      label: "deparment_name",
                      value: "_id"
                    }}
                    options={deptsd}
                    defaultValue="655e32cfc44fbd3bafb19b81"
                    style={{ width: 120 }}
                  />
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
          <Form.Item>
            <Row>
              <Col xs={2} sm={1} md={3} lg={2}>
                <Form.Item>
                  <Button type="primary" htmlType="submit">
                    提交
                  </Button>
                </Form.Item>
              </Col>
              <Col>
                <Form.Item>
                  <Button type="primary" onClick={() => navigate("/admin/conference")}>
                    返回
                  </Button>
                </Form.Item>
              </Col>
            </Row>
          </Form.Item>
        </Form>
      </div>
      <div>{contextHolder}</div>
      <div>{contextHolders}</div>
    </div>
  )
}

export default Index
